package com.qf.web.controller;

import com.qf.domain.*;
import com.qf.service.AddressService;
import com.qf.service.CartService;
import com.qf.service.OrderService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.RandomUtil;
import com.qf.utils.StringUtils;
import com.sun.org.apache.xpath.internal.operations.Or;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * projectName:myxiaomi
 * author:LiPengChong
 * time:2024/4/15 17:21
 * description:
 */
@WebServlet("/orderservlet")
public class OrderServlet extends BaseServlet {
    //【添加订单】
    //orderservlet?method=addOrder&aid=8
    public String addOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String aid = request.getParameter("aid");
        //非空验证
        if (StringUtils.isEmpty(aid)) {
            request.setAttribute("msg", "地址不能为空");
            return "/message.jsp";
        }
        try {
            //3.调用业务逻辑
            OrderService orderService = new OrderServiceImpl();
            //3.1从购物车中获取money
            CartService cartService = new CartServiceImpl();//调用购物车的业务层
            List<Cart> cartList = cartService.find(user.getId());//通过用户id查询用户购物车
            if (cartList == null || cartList.size() == 0) {
                request.setAttribute("msg", "购物车不能为空");
                return "/message.jsp";
            }
            BigDecimal money = new BigDecimal(0);
            for (Cart cart : cartList) {
                money = money.add(cart.getMoney());
            }
            //3.2创建一个订单号
            String oid = RandomUtil.createOrderId();
            //状态 1未支付 2已支付,代发货 3已发货,待收货 4订单完成

            Order order = new Order(oid, user.getId(), money, "1", LocalDateTime.now(), Integer.parseInt(aid));
            orderService.submitOrder(order, cartList);//submitOrder提交订单
            request.setAttribute("order", order);
            return "/orderSuccess.jsp";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加订单失败" + e.getMessage());
            return "/message.jsp";

        }
    }

    /*【预览订单】
     * 预览订单中的信息包括：商品表的商品名，商品价格。
     *                   购物车的数量，价格
     *                   地址表的地址
     * （涉及到三张表的信息）
     * */
//    http://localhost:8080/orderservlet?method=getOrderView
    public String getOrderView(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            //2.调用业务逻辑
            CartService cartService = new CartServiceImpl();
            List<Cart> cartList = cartService.find(user.getId());//通过用户id找到用户的所有商品信息，返回一个商品集合
            //3.获取地址
            AddressService addressService = new AddressServiceImpl();
            List<Address> addList = addressService.find(user.getId());//通过用户id找到用户所有的地址
            //存储数据
            request.setAttribute("cartList", cartList);
            request.setAttribute("addList", addList);
            return "/order.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "预览订单失败" + e.getMessage());
            return "/message.jsp";
        }
    }


    //【获取订单列表】
    //http://localhost:8080/orderservlet?method=getOrderList
    public String getOrderList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            //2.调用业务逻辑
            OrderService orderService = new OrderServiceImpl();
            List<Order> orderList = orderService.find(user.getId());
            //存值
            request.setAttribute("orderList", orderList);
            return "/orderList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "获取订单列表失败" + e.getMessage());
            return "/message.jsp";
        }

    }


    //【查看某个订单的详情】
    //http://localhost:8080/orderservlet?method=getOrderDetail&oid=202404182237509572422638
    public String getOrderDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String oid = request.getParameter("oid");
        //非空验证
        if (StringUtils.isEmpty(oid)){
            request.setAttribute("msg", "订单编号不能为空");
            return "/message.jsp";
        }
        try {
            //3.调用业务逻辑
            OrderService orderService = new OrderServiceImpl();
            //3.1查看订单
            Order order = orderService.findByOid(oid);
            //3.2订单详情
            List<OrderDetail> orderDetails = orderService.findDetail(oid);
            //存值
            request.setAttribute("order",order);
            request.setAttribute("orderDetails",orderDetails);
            return "/orderDetail.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "获取订单详情失败" + e.getMessage());
            return "/message.jsp";
        }
    }


/*-------------------------------------------------后台查询订单模块---------------------------------------------------------------------------*/
    //【查询所有用户订单】
    //orderservlet?method=sendOrder
    public String searchOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端数据
        String username = request.getParameter("username");
        String orderStatus = request.getParameter("orderStatus");

        //2.创建可变长字符串，和参数集合
        StringBuilder where = new StringBuilder(" where 1=1 ");
        List<Object> params = new ArrayList<>();
        //非空验证
        if (!StringUtils.isEmpty(username)){
            where.append("usrname=?");
            params.add(username);
        }
        if (!StringUtils.isEmpty(orderStatus)){
            where.append("and status=? ");
            params.add(orderStatus);
        }
        //3.调用业务逻辑
        
        return "/admin/showAllOrder.jsp";
    }
}

